package vn.cuhanh.fragment;

import vn.cuhanh.BaseActivity;
import vn.cuhanh.ChangeAvatarActivity;
import vn.cuhanh.MainActivity;
import vn.cuhanh.R;
import vn.cuhanh.ShareActivity;
import vn.cuhanh.bean.CharInfo;
import vn.cuhanh.bean.ShareInfo;
import vn.cuhanh.models.Model_CharInfo;
import vn.cuhanh.utils.HelperFunc;
import vn.cuhanh.utils.ShareZingMe;
import vn.cuhanh.utils.ViewHelper;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CharacterInfoFragment extends BasicFragment {
	
	private static String GA_CATEGORY = "charInfo_fragment";

	private Context ctx;
	private View view;
	private int charId;
	private View tabInfo;
	private View tabCommunity;
	private View tabTournament;
	private TextView tabControllInfo;
	private TextView tabControllCommunity;
	private TextView tabControllTournament;
	public static CharInfo charInfo;
	private LinearLayout contentWrapper;
	private View noNetworkScreen;
	private View noCharInfoScreen;
	private View loadingScreen;
	
	public Handler handler = new Handler();
	
	public static CharacterInfoFragment newInstance(Context ctx,
			int charId) {

		return new CharacterInfoFragment(ctx, charId);
	}

	public CharacterInfoFragment(Context ctx, int charId) {
		super(ctx);
		this.ctx = ctx;
		this.setCharId(charId);
	}

	public CharacterInfoFragment() {
		super();
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// setUserVisibleHint(true);
	}

	@Override
	public void onPause() {
		super.onPause();
		// HelperFunc.unbindDrawables(view);
		// System.gc();
	}

	@Override
	public void onDestroy() {

		super.onDestroy();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		View footer = view.findViewById(R.id.footer);
		BaseActivity.updateDndScore(footer);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.character_info, null);
		try {
			if (ctx == null || view == null) {
				if (isAdded()) {
					ctx = getActivity();
				} else {
					return view;
				}
			}
			
			tabInfo = view.findViewById(R.id.char_info_tab_info);
			tabCommunity = view.findViewById(R.id.char_info_tab_community);
			tabTournament = view.findViewById(R.id.char_info_tab_tournament);
			contentWrapper = (LinearLayout)view.findViewById(R.id.char_info_content_wrapper);
			loadingScreen = view.findViewById(R.id.char_info_loading);
	        
			noCharInfoScreen = view.findViewById(R.id.char_info_no_charinfo);
			Button btnCreateChar = (Button) view.findViewById(R.id.char_info_create_char);
			btnCreateChar.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					HelperFunc.trackEvent(ctx, GA_CATEGORY, "btn_create_char_press", "btn_create_char_press");
					Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://3q.com.vn"));
					startActivity(browserIntent);
				}
			});
			noNetworkScreen = view.findViewById(R.id.char_info_no_network);
			noNetworkScreen.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					loadCharInfo();
				}
			});
			
			initTabControll();
			showTabInfo();
			loadCharInfo();
			
			setBtnShareListener();

			return view;
		} catch (InflateException e) {
			HelperFunc.readStackTrace(e);
		} catch (Exception e) {
			HelperFunc.readStackTrace(e);
		}
		return view;
	}
	
	private void loadCharInfo() {
		if(!MainActivity.isLogin || MainActivity.username == null) {
			return;
		}
		try {
			charInfo = Model_CharInfo.getCharInfo(ctx, MainActivity.username);
			if(charInfo != null && !charInfo.isExpired()) {
				this.fillCharInfo();
				return;
			}
			showLoadingScreen();
			Thread thread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					final int result = Model_CharInfo.loadCharInfoFromInternet(ctx);
					handler.post(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							switch (result) {
							case 2: //no network but local saved charInfo still exist.
							case 1: //success
								fillCharInfo();
								break;
							case 0: //unknown error
								showNoNetwork();
								break;
							case -1: //no network
								showNoNetwork();
								break;
							default:
								showNoCharInfoFound();
								break;
							}
						}
					});
				}
			});
			thread.start();
		} catch (Exception e) {
			// TODO: handle exception
			HelperFunc.readStackTrace(e);
		}
	}

	public int getCharId() {
		return charId;
	}

	public void setCharId(int charId) {
		this.charId = charId;
	}
	
	public void initTabControll() {
		if(view == null) {
			return;
		}
		OnTabControllClickHandler onClickHandler = new OnTabControllClickHandler();
		tabControllInfo = (TextView) view.findViewById(R.id.char_info_tabcontroll_info);
		tabControllInfo.setOnClickListener(onClickHandler);
		tabControllCommunity = (TextView) view.findViewById(R.id.char_info_tabcontroll_community);
		tabControllCommunity.setOnClickListener(onClickHandler);
		tabControllTournament = (TextView) view.findViewById(R.id.char_info_tabcontroll_tournament);
		tabControllTournament.setOnClickListener(onClickHandler);
	}
	
	public void setTabActive(View v) {
		v.setBackgroundColor(0xFFFFFFFF);
		View parent = (View)v.getParent();
		parent.setBackgroundColor(0xFFFFFFFF);
	}
	
	public void setTabInActive(View v) {
		v.setBackgroundColor(0xFFF0F0F0);
		View parent = (View)v.getParent();
		parent.setBackgroundColor(0xFF9F9F9F);
	}
	
	public void showTabInfo() {
		tabInfo.setVisibility(View.VISIBLE);
		tabCommunity.setVisibility(View.GONE);
		tabTournament.setVisibility(View.GONE);
		setTabActive(tabControllInfo);
		setTabInActive(tabControllCommunity);
		setTabInActive(tabControllTournament);
	}
	public void showTabCommunity() {
		tabInfo.setVisibility(View.GONE);
		tabCommunity.setVisibility(View.VISIBLE);
		tabTournament.setVisibility(View.GONE);
		setTabInActive(tabControllInfo);
		setTabActive(tabControllCommunity);
		setTabInActive(tabControllTournament);
	}
	public void showTabTournament() {
		tabInfo.setVisibility(View.GONE);
		tabCommunity.setVisibility(View.GONE);
		tabTournament.setVisibility(View.VISIBLE);
		setTabInActive(tabControllInfo);
		setTabInActive(tabControllCommunity);
		setTabActive(tabControllTournament);
	}
	
	public class OnTabControllClickHandler implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			HelperFunc.trackEvent(ctx, GA_CATEGORY, "tab_controll_press", "tab_controll_press");
			if(v == null) {
				return;
			}
			switch (v.getId()) {
			case R.id.char_info_tabcontroll_info:
				showTabInfo();
				break;
			case R.id.char_info_tabcontroll_community:
				showTabCommunity();
				break;
			case R.id.char_info_tabcontroll_tournament:
				showTabTournament();
				break;
			default:
				break;
			}
		}
		
	}
	
	public void showLoadingScreen() {
		ViewHelper.initLoadingFrame(ctx, loadingScreen);
		contentWrapper.setVisibility(View.GONE);
		noNetworkScreen.setVisibility(View.GONE);
		noCharInfoScreen.setVisibility(View.GONE);
		loadingScreen.setVisibility(View.VISIBLE);
	}
	
	public void showNoNetwork() {
		contentWrapper.setVisibility(View.GONE);
		noNetworkScreen.setVisibility(View.VISIBLE);
		noCharInfoScreen.setVisibility(View.GONE);
		loadingScreen.setVisibility(View.GONE);
	}
	
	public void showNoCharInfoFound() {
		contentWrapper.setVisibility(View.GONE);
		noNetworkScreen.setVisibility(View.GONE);
		noCharInfoScreen.setVisibility(View.VISIBLE);
		loadingScreen.setVisibility(View.GONE);
	}
	
	public void showContent() {
		contentWrapper.setVisibility(View.VISIBLE);
		noNetworkScreen.setVisibility(View.GONE);
		noCharInfoScreen.setVisibility(View.GONE);
		loadingScreen.setVisibility(View.GONE);
	}
	
	public void openShareScreen() {
		if(ShareActivity.shareInfo == null) {
			return;
		}
		Intent intent = new Intent(ctx, ShareActivity.class);
		startActivity(intent);
	}
	
	public static String getCharName() {
		if(charInfo != null) {
			return charInfo.getName();
		}
		if(MainActivity.userAccount != null) {
			return MainActivity.userAccount.getZingMeName();
		}
		if(MainActivity.username != null) {
			return MainActivity.username;
		}
		HelperFunc.readStackTrace(new Exception("Can not get char_name."));
		return "";
	}
	
	public void setBtnShareListener() {
		(view.findViewById(R.id.char_info_level_btn_share)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ctx, "share", "bt_share_press", "bt_share_level_press");
				ShareActivity.shareInfo = new ShareInfo(
						ShareZingMe.getRandomFunnyPhrase(ctx), 
						ctx.getResources().getString(R.string.char_info_level_share_title), 
						ctx.getResources().getString(R.string.char_info_level_share_description)
							.replace("char_name", getCharName())
							.replace("level_name", charInfo != null ? Model_CharInfo.getLevelInfoFromScore(ctx, Integer.valueOf(charInfo.getScore().toString())) : ""),
						ctx.getResources().getString(R.string.char_info_level_share_imgurl), 
						ctx.getResources().getString(R.string.char_info_level_share_local_img), 
						ctx.getResources().getString(R.string.char_info_level_share_link), 
						ctx.getResources().getString(R.string.char_info_level_share_state),
						ctx.getResources().getInteger(R.integer.actionIdShareLevel));
				openShareScreen();
			}
		});
		(view.findViewById(R.id.char_info_charm_btn_share)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ctx, "share", "bt_share_press", "bt_share_charm_press");
				ShareActivity.shareInfo = new ShareInfo(
						ShareZingMe.getRandomFunnyPhrase(ctx), 
						ctx.getResources().getString(R.string.char_info_charm_share_title), 
						ctx.getResources().getString(R.string.char_info_charm_share_description)
							.replace("char_name", getCharName())
							.replace("charm_score", charInfo != null ? String.valueOf(charInfo.getCharm()) : ""),
						ctx.getResources().getString(R.string.char_info_charm_share_imgurl), 
						ctx.getResources().getString(R.string.char_info_charm_share_local_img), 
						ctx.getResources().getString(R.string.char_info_charm_share_link), 
						ctx.getResources().getString(R.string.char_info_charm_share_state),
						ctx.getResources().getInteger(R.integer.actionIdShareCharm));
				openShareScreen();
			}
		});
		(view.findViewById(R.id.char_info_flower_btn_share)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ctx, "share", "bt_share_press", "bt_share_charm_press");
				ShareActivity.shareInfo = new ShareInfo(
						ShareZingMe.getRandomFunnyPhrase(ctx), 
						ctx.getResources().getString(R.string.char_info_flower_share_title), 
						ctx.getResources().getString(R.string.char_info_flower_share_description)
							.replace("char_name", getCharName())
							.replace("flower_number", charInfo != null ? String.valueOf(charInfo.getFlower()) : ""), 
						ctx.getResources().getString(R.string.char_info_flower_share_imgurl), 
						ctx.getResources().getString(R.string.char_info_flower_share_local_img), 
						ctx.getResources().getString(R.string.char_info_flower_share_link), 
						ctx.getResources().getString(R.string.char_info_flower_share_state),
						ctx.getResources().getInteger(R.integer.actionIdShareFlower));
				openShareScreen();
			}
		});
		(view.findViewById(R.id.char_info_eggs_btn_share)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ctx, "share", "bt_share_press", "bt_share_eggs_press");
				ShareActivity.shareInfo = new ShareInfo(
						ShareZingMe.getRandomFunnyPhrase(ctx), 
						ctx.getResources().getString(R.string.char_info_eggs_share_title), 
						ctx.getResources().getString(R.string.char_info_eggs_share_description)
							.replace("char_name", getCharName())
							.replace("eggs_number", charInfo != null ? String.valueOf(charInfo.getEggs()) : ""), 
						ctx.getResources().getString(R.string.char_info_eggs_share_imgurl), 
						ctx.getResources().getString(R.string.char_info_eggs_share_local_img), 
						ctx.getResources().getString(R.string.char_info_eggs_share_link), 
						ctx.getResources().getString(R.string.char_info_eggs_share_state),
						0);
				openShareScreen();
			}
		});
		(view.findViewById(R.id.char_info_online_time_btn_share)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ctx, "share", "bt_share_press", "bt_share_online_time_press");
				ShareActivity.shareInfo = new ShareInfo(
						ShareZingMe.getRandomFunnyPhrase(ctx), 
						ctx.getResources().getString(R.string.char_info_online_time_share_title), 
						ctx.getResources().getString(R.string.char_info_online_time_share_description)
							.replace("char_name", getCharName())
							.replace("online_time", charInfo != null ? HelperFunc.secondToTime(ctx, charInfo.getOnline_time()) : ""), 
						ctx.getResources().getString(R.string.char_info_online_time_share_imgurl),
						ctx.getResources().getString(R.string.char_info_online_time_share_local_img),
						ctx.getResources().getString(R.string.char_info_online_time_share_link), 
						ctx.getResources().getString(R.string.char_info_online_time_share_state),
						0);
				openShareScreen();
			}
		});
		(view.findViewById(R.id.char_info_m3g_money_btn_share)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ctx, "share", "bt_share_press", "bt_share_m3g_money_press");
				ShareActivity.shareInfo = new ShareInfo(
						ShareZingMe.getRandomFunnyPhrase(ctx), 
						ctx.getResources().getString(R.string.char_info_m3g_money_share_title), 
						ctx.getResources().getString(R.string.char_info_m3g_money_share_description)
							.replace("char_name", getCharName())
							.replace("m3g_money", charInfo != null ? String.valueOf(charInfo.getM3g_money()) : ""), 
						ctx.getResources().getString(R.string.char_info_m3g_money_share_imgurl), 
						ctx.getResources().getString(R.string.char_info_m3g_money_share_local_img), 
						ctx.getResources().getString(R.string.char_info_m3g_money_share_link), 
						ctx.getResources().getString(R.string.char_info_m3g_money_share_state),
						0);
				openShareScreen();
			}
		});
		(view.findViewById(R.id.char_info_food_btn_share)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ctx, "share", "bt_share_press", "bt_share_food_press");
				ShareActivity.shareInfo = new ShareInfo(
						ShareZingMe.getRandomFunnyPhrase(ctx), 
						ctx.getResources().getString(R.string.char_info_food_share_title), 
						ctx.getResources().getString(R.string.char_info_food_share_description)
							.replace("char_name", getCharName())
							.replace("food_number", charInfo != null ? String.valueOf(charInfo.getFood()) : ""), 
						ctx.getResources().getString(R.string.char_info_food_share_imgurl), 
						ctx.getResources().getString(R.string.char_info_food_share_local_img), 
						ctx.getResources().getString(R.string.char_info_food_share_link), 
						ctx.getResources().getString(R.string.char_info_food_share_state),
						0);
				openShareScreen();
			}
		});
		(view.findViewById(R.id.char_info_soldiers_btn_share)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ctx, "share", "bt_share_press", "bt_share_soldiers_press");
				ShareActivity.shareInfo = new ShareInfo(
						ShareZingMe.getRandomFunnyPhrase(ctx), 
						ctx.getResources().getString(R.string.char_info_soldiers_share_title), 
						ctx.getResources().getString(R.string.char_info_soldiers_share_description)
							.replace("char_name", getCharName())
							.replace("soldier_number", charInfo != null ? String.valueOf(charInfo.getSoldier()) : ""), 
						ctx.getResources().getString(R.string.char_info_soldiers_share_imgurl),
						ctx.getResources().getString(R.string.char_info_soldiers_share_local_img),
						ctx.getResources().getString(R.string.char_info_soldiers_share_link), 
						ctx.getResources().getString(R.string.char_info_soldiers_share_state),
						0);
				openShareScreen();
			}
		});
	}
	
	public void fillCharInfo() {
		if(charInfo == null) {
			showNoCharInfoFound();
			return;
		}
		showContent();
		ImageView avatar = (ImageView)view.findViewById(R.id.char_info_avatar);
		try {
			if(MainActivity.userAccount != null) {
				avatar.setImageBitmap(HelperFunc.getBitmapFromAsset(this.ctx, this.ctx.getResources().getString(R.string.avatar_file_name).replace("number", String.valueOf(MainActivity.userAccount.getAvatarNumber()))));
			}
		} catch (Exception e) {
			// TODO: handle exception
			HelperFunc.readStackTrace(e);
		}
		avatar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ctx, GA_CATEGORY, "bt_change_avatar_press", "bt_change_avatar_press");
				Intent intent = new Intent(ctx, ChangeAvatarActivity.class);
				intent.putExtra("vn.cuhanh.changeAvatarActivity.currentAvatarNumber", MainActivity.userAccount != null ? MainActivity.userAccount.getAvatarNumber() : 0);
				startActivity(intent);
			}
		});
		((TextView)view.findViewById(R.id.char_info_display_name)).setText(charInfo.getName());
		((TextView)view.findViewById(R.id.char_info_user_name)).setText(
				ctx.getResources().getString(R.string.char_info_account_name) + ": " + MainActivity.username);
		((TextView)view.findViewById(R.id.char_info_level)).setText(
				ctx.getResources().getString(R.string.char_info_level) + ": " + Model_CharInfo.getLevelInfoFromScore(ctx, Integer.valueOf(charInfo.getScore().toString())));
		((TextView)view.findViewById(R.id.char_info_user_id)).setText(
				ctx.getResources().getString(R.string.char_info_account_id) + ": " + charInfo.getId().toString());
		((TextView)view.findViewById(R.id.char_info_gender)).setText(
				ctx.getResources().getString(R.string.char_info_sex) + ": " + charInfo.getSex());
		((TextView)view.findViewById(R.id.char_info_mate_with)).setText(
				ctx.getResources().getString(R.string.char_info_mate) + ": " + charInfo.getMate_name().toString());
		((TextView)view.findViewById(R.id.char_info_charm)).setText(
				ctx.getResources().getString(R.string.char_info_charm) + ": " + charInfo.getCharm().toString());
		((TextView)view.findViewById(R.id.char_info_flower)).setText(
				ctx.getResources().getString(R.string.char_info_flower) + ": " + charInfo.getFlower().toString());
		((TextView)view.findViewById(R.id.char_info_eggs)).setText(
				ctx.getResources().getString(R.string.char_info_eggs) + ": " + charInfo.getEggs().toString());
		((TextView)view.findViewById(R.id.char_info_online_time)).setText(
				ctx.getResources().getString(R.string.char_info_online) + ": " + HelperFunc.secondToTime(ctx, Integer.valueOf(charInfo.getOnline_time().toString())));
		((TextView)view.findViewById(R.id.char_info_m3g_money)).setText(
				ctx.getResources().getString(R.string.char_info_m3g_money) + ": " + charInfo.getM3g_money().toString());
		((TextView)view.findViewById(R.id.char_info_food)).setText(
				ctx.getResources().getString(R.string.char_info_food) + ": " + charInfo.getFood().toString());
		((TextView)view.findViewById(R.id.char_info_soldier)).setText(
				ctx.getResources().getString(R.string.char_info_soldier) + ": " + charInfo.getSoldier().toString());
	}
}
